var fs = require('fs');
var dateFormat = require('dateformat');
var os = require('os');


function logError(err, consolePrint) {
	var now = new Date();
	var errStr = dateFormat(now, "isoDateTime") + ' - ';
	
	if (typeof err == "string") {
		errStr += err;
	} else if (err.stack) {
		errStr += err.stack.toString();
	} else if (err.toString && errStr.toString() != '[object Object]') {
		errStr += err.toString();
	} else {
		errStr += "Cannot log the error. [object Object] given or Unknown type.";
	}

	if (consolePrint) {
		console.log(err);
	}

	fs.writeFile(_ROOT + '/app/logs/error.log', errStr + os.EOL, {
		flag: 'a'
	}, function() {
		console.error('An error has been logged to the log file.');
	});
}


module.exports = {
	log: logError
};